import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Button,
  IconButton,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Pagination,
  Chip,
  Alert,
  Snackbar,
  CircularProgress,
  Grid,
  FormHelperText,
  Autocomplete,
  Switch,
  FormControlLabel
} from '@mui/material';
import {
  Delete as DeleteIcon,
  Edit as EditIcon,
  Add as AddIcon,
  Link as LinkIcon,
  Search as SearchIcon
} from '@mui/icons-material';
import { PromotionService, Promotion } from '../../promotion/services/PromotionService';
import { PromotionResourceService } from '../../promotion/services/PromotionResourceService';
import { ResourceService, Resource } from '../../resources/services/ResourceService';
import { DateTimePicker } from '@mui/x-date-pickers/DateTimePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { zhCN } from 'date-fns/locale';

interface PromotionFormData {
  title: string; // 用作promotionTitle
  promotionRule: string;
  startTime: Date | null;
  endTime: Date | null;
  isActive: boolean;
  discount: number;
}

const initialFormData: PromotionFormData = {
  title: '',
  promotionRule: '',
  startTime: null,
  endTime: null,
  isActive: true,
  discount: 0
};

const PromotionManagement: React.FC = () => {
  const [promotions, setPromotions] = useState<Promotion[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState<number>(1);
  const [totalPages, setTotalPages] = useState<number>(1);
  const [selectedPromotion, setSelectedPromotion] = useState<Promotion | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState<boolean>(false);
  const [formDialogOpen, setFormDialogOpen] = useState<boolean>(false);
  const [linkResourceDialogOpen, setLinkResourceDialogOpen] = useState<boolean>(false);
  const [formData, setFormData] = useState<PromotionFormData>(initialFormData);
  const [formErrors, setFormErrors] = useState<Partial<Record<keyof PromotionFormData, string>>>({});
  const [isEditMode, setIsEditMode] = useState<boolean>(false);
  const [snackbar, setSnackbar] = useState<{open: boolean, message: string, severity: 'success' | 'error'}>({open: false, message: '', severity: 'success'});
  const [resources, setResources] = useState<Resource[]>([]);
  const [selectedResources, setSelectedResources] = useState<Resource[]>([]);
  const [searchQuery, setSearchQuery] = useState<string>('');
  const [searchType, setSearchType] = useState<string>('title'); // 'id' 或 'title'
  const [linkedResources, setLinkedResources] = useState<Resource[]>([]);

  // 添加一个状态变量来存储所有原始数据
  const [allPromotions, setAllPromotions] = useState<Promotion[]>([]);

  const pageSize = 10;

  useEffect(() => {
    fetchPromotions();
  }, [page]);

  const fetchPromotions = async () => {
    try {
      setLoading(true);
      setError(null);
      
      // 使用新的方法获取所有促销活动（不分页）
      const allPromotionsData = await PromotionService.getAllPromotions();
      
      // 设置促销活动数据
      setPromotions(allPromotionsData);
      setAllPromotions(allPromotionsData); // 保存所有数据用于前端筛选
      // 由于不再分页，设置总页数为1
      setTotalPages(1);
    } catch (err) {
      setError(err instanceof Error ? err.message : '获取促销活动列表失败');
      setPromotions([]); // 确保在API调用失败时promotions被设置为空数组
      setAllPromotions([]); // 同时清空allPromotions
    } finally {
      setLoading(false);
    }
  };

  const fetchResources = async () => {
    try {
      const response = await ResourceService.getResourceList(1, 100); // 获取更多资源用于选择
      setResources(response.records);
    } catch (err) {
      setSnackbar({open: true, message: err instanceof Error ? err.message : '获取资源列表失败', severity: 'error'});
    }
  };

  const fetchLinkedResources = async (promotionId: string) => {
    try {
      const resources = await PromotionResourceService.getPromotionResources(promotionId);
      console.log('API返回的资源数据:', resources);
      setLinkedResources(resources);
      console.log('设置linkedResources后的状态:', resources);
      
      // 获取每个资源的详细信息
      resources.forEach(item => {
        if (!item.resource && item.resourceId) {
          fetchResourceDetail(item.resourceId);
        }
      });
    } catch (err) {
      setSnackbar({open: true, message: err instanceof Error ? err.message : '获取关联资源失败', severity: 'error'});
    }
  };

  const handlePageChange = (event: React.ChangeEvent<unknown>, value: number) => {
    setPage(value);
  };

  const handleDeleteClick = (promotion: Promotion) => {
    setSelectedPromotion(promotion);
    setDeleteDialogOpen(true);
  };

  const handleDeleteConfirm = async () => {
    if (!selectedPromotion) return;
    
    try {
      // 确保selectedPromotion有id字段
      const promotionId = selectedPromotion.id || selectedPromotion.promotionId;
      if (!promotionId) {
        throw new Error('促销活动ID不能为空');
      }
      
      // 确保id是字符串类型
      const idStr = String(promotionId);
      
      // 先删除该促销活动的所有关联资源
      await PromotionResourceService.deleteByPromotionId(idStr);
      
      // 然后删除促销活动
      await PromotionService.deletePromotion(idStr);
      setSnackbar({open: true, message: '促销活动及其关联资源删除成功', severity: 'success'});
      fetchPromotions(); // 重新加载促销活动列表
    } catch (err) {
      setSnackbar({open: true, message: err instanceof Error ? err.message : '删除促销活动失败', severity: 'error'});
    } finally {
      setDeleteDialogOpen(false);
      setSelectedPromotion(null);
    }
  };

  const handleAddClick = () => {
    setFormData(initialFormData);
    setFormErrors({});
    setIsEditMode(false);
    setFormDialogOpen(true);
  };

  const handleEditClick = (promotion: Promotion) => {
    // 确保保存promotion对象时包含id信息
    const promotionWithId = {
      ...promotion,
      // 如果id存在则使用id，否则使用promotionId
      id: promotion.id || promotion.promotionId
    };
    setSelectedPromotion(promotionWithId);
    setFormData({
      title: promotion.promotionTitle,
      promotionRule: promotion.promotionRule,
      startTime: new Date(promotion.startTime || ''),
      endTime: new Date(promotion.endTime || ''),
      isActive: promotion.isActive,
      discount: promotion.discount
    });
    setFormErrors({});
    setIsEditMode(true);
    setFormDialogOpen(true);
  };

  const handleStatusChange = async (promotion: Promotion, newStatus: boolean) => {
    try {
      // 确保promotion有id字段
      const promotionId = promotion.id || promotion.promotionId;
      if (!promotionId) {
        throw new Error('促销活动ID不能为空');
      }
      
      // 确保id是字符串类型
      const idStr = String(promotionId);
      
      await PromotionService.updatePromotionStatus(idStr, newStatus);
      setSnackbar({open: true, message: `促销活动状态已${newStatus ? '激活' : '停用'}`, severity: 'success'});
      fetchPromotions(); // 重新加载促销活动列表
    } catch (err) {
      setSnackbar({open: true, message: err instanceof Error ? err.message : '更新促销活动状态失败', severity: 'error'});
    }
  };

  const handleLinkResourcesClick = (promotion: Promotion) => {
    setSelectedPromotion(promotion);
    setSelectedResources([]);
    fetchResources();
    
    // 获取已关联的资源列表
    const promotionId = promotion.id || promotion.promotionId;
    if (promotionId) {
      fetchLinkedResources(String(promotionId));
    }
    
    setLinkResourceDialogOpen(true);
  };

  const handleFormChange = (field: keyof PromotionFormData, value: any) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // 清除该字段的错误
    if (formErrors[field]) {
      setFormErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  const validateForm = (): boolean => {
    const errors: Partial<Record<keyof PromotionFormData, string>> = {};
    
    if (!formData.title.trim()) {
      errors.title = '标题不能为空';
    }
    
    if (!formData.promotionRule.trim()) {
      errors.promotionRule = '活动规则不能为空';
    }
    
    if (!formData.startTime) {
      errors.startTime = '开始时间不能为空';
    }
    
    if (!formData.endTime) {
      errors.endTime = '结束时间不能为空';
    }
    
    if (formData.startTime && formData.endTime && formData.startTime > formData.endTime) {
      errors.endTime = '结束时间不能早于开始时间';
    }
    
    if (formData.discount < 0) {
      errors.discount = '折扣不能为负数';
    }
    
    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleFormSubmit = async () => {
    if (!validateForm()) return;
    
    try {
      // 格式化日期时间为后端需要的格式 YYYY-MM-DD HH:MM:SS
      const formatDateTime = (date: Date | null): string => {
        if (!date) return '';
        // 使用更兼容的日期格式，避免ISO格式可能导致的解析问题
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      };

      if (isEditMode && selectedPromotion) {
        // 确保selectedPromotion有id字段
        const promotionId = selectedPromotion.id || selectedPromotion.promotionId;
        if (!promotionId) {
          throw new Error('促销活动ID不能为空');
        }
        
        // 确保id是字符串类型
        const idStr = String(promotionId);
        
        await PromotionService.updatePromotion(idStr, {
          promotionId: parseInt(idStr), // 添加promotionId字段并转换为整数
          promotionTitle: formData.title,
          promotionRule: formData.promotionRule,
          startTime: formatDateTime(formData.startTime),
          endTime: formatDateTime(formData.endTime),
          isActive: formData.isActive,
          discount: formData.discount
        });
        setSnackbar({open: true, message: '促销活动更新成功', severity: 'success'});
      } else {
        // 创建新的促销活动
        await PromotionService.createPromotion({
          title: formData.title,
          promotionRule: formData.promotionRule,
          startTime: formatDateTime(formData.startTime),
          endTime: formatDateTime(formData.endTime),
          isActive: formData.isActive,
          discount: formData.discount
        });
        setSnackbar({open: true, message: '促销活动创建成功', severity: 'success'});
      }
      
      setFormDialogOpen(false);
      fetchPromotions(); // 重新加载促销活动列表
    } catch (err) {
      setSnackbar({open: true, message: err instanceof Error ? err.message : '保存促销活动失败', severity: 'error'});
    }
  };

  const handleLinkResourcesSubmit = async () => {
    if (!selectedPromotion || selectedResources.length === 0) return;
    
    try {
      // 确保selectedPromotion有id字段
      const promotionId = selectedPromotion.id || selectedPromotion.promotionId;
      if (!promotionId) {
        throw new Error('促销活动ID不能为空');
      }
      
      // 确保id是字符串类型
      const idStr = String(promotionId);
      
      // 调用关联资源的API
      await PromotionService.linkResourcesToPromotion(
        idStr, 
        selectedResources.map(r => r.id)
      );
      
      // 重新获取关联资源列表
      fetchLinkedResources(idStr);
      
      // 清空已选资源列表，以便用户可以继续选择其他资源
      setSelectedResources([]);
      
      setSnackbar({open: true, message: '资源关联成功', severity: 'success'});
      // 不关闭对话框，让用户可以继续关联其他资源
    } catch (err) {
      setSnackbar({open: true, message: err instanceof Error ? err.message : '关联资源失败', severity: 'error'});
    }
  };

  const handleSnackbarClose = () => {
    setSnackbar({...snackbar, open: false});
  };

  const handleSearchChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const value = event.target.value;
    setSearchQuery(value);
    
    // 直接在输入变化时进行前端筛选
    if (!value.trim()) {
      // 如果搜索关键词为空，则显示所有促销活动
      setPromotions(allPromotions);
      return;
    }
    
    try {
      setError(null);
      
      // 前端筛选
      let filteredPromotions = [];
      if (searchType === 'id') {
        // 验证ID是否为数字
        if (!/^\d+$/.test(value.trim())) {
          throw new Error('ID必须是数字');
        }
        filteredPromotions = allPromotions.filter(promotion => {
          const promotionId = promotion.id || promotion.promotionId;
          return promotionId && promotionId.toString().includes(value.trim());
        });
      } else if (searchType === 'title') {
        filteredPromotions = allPromotions.filter(promotion => 
          promotion.promotionTitle && promotion.promotionTitle.toLowerCase().includes(value.trim().toLowerCase())
        );
      }
      
      // 更新促销活动列表
      setPromotions(filteredPromotions);
    } catch (err) {
      setError(err instanceof Error ? err.message : '搜索促销活动失败');
      setPromotions([]); // 确保在搜索失败时promotions被设置为空数组
    }
  };

  const handleSearchTypeChange = (event: React.ChangeEvent<{ value: unknown }>) => {
    setSearchType(event.target.value as string);
    // 当搜索类型变化时，重新执行搜索
    if (searchQuery.trim()) {
      handleSearchChange({ target: { value: searchQuery } } as React.ChangeEvent<HTMLInputElement>);
    }
  };

  // 删除 handleSearch 函数，因为我们现在在输入变化时直接进行筛选

  const handleRemoveResourceClick = (relationId: string) => {
    setResourceToRemove(relationId);
    setRemoveResourceDialogOpen(true);
  };

  const handleRemoveResource = async () => {
    if (!selectedPromotion?.id && !selectedPromotion?.promotionId) return;
    if (!resourceToRemove) return;
    
    try {
      const promotionId = selectedPromotion.id || selectedPromotion.promotionId;
      await PromotionResourceService.deletePromotionResource(resourceToRemove);
      
      // 重新获取关联资源列表
      fetchLinkedResources(String(promotionId));
      
      setSnackbar({open: true, message: '解除资源关联成功', severity: 'success'});
    } catch (err) {
      setSnackbar({open: true, message: err instanceof Error ? err.message : '解除资源关联失败', severity: 'error'});
    } finally {
      setRemoveResourceDialogOpen(false);
      setResourceToRemove('');
    }
  };

  const handleRemoveAllResourcesClick = () => {
    setRemoveAllResourcesDialogOpen(true);
  };

  // 删除促销活动下的所有关联资源
  const handleRemoveAllResources = async () => {
    if (!selectedPromotion?.id && !selectedPromotion?.promotionId) return;
    
    try {
      const promotionId = selectedPromotion.id || selectedPromotion.promotionId;
      await PromotionResourceService.deleteByPromotionId(String(promotionId));
      
      // 清空关联资源列表
      setLinkedResources([]);
      
      setSnackbar({open: true, message: '已删除所有关联资源', severity: 'success'});
    } catch (err) {
      setSnackbar({open: true, message: err instanceof Error ? err.message : '删除所有关联资源失败', severity: 'error'});
    } finally {
      setRemoveAllResourcesDialogOpen(false);
    }
  };

  // 获取单个资源详情
  const fetchResourceDetail = async (resourceId: string) => {
    try {
      const resourceDetail = await ResourceService.getResourceById(resourceId);
      // 更新linkedResources中对应的资源信息
      setLinkedResources(prev => prev.map(item => {
        if (item.resourceId === resourceId) {
          return { ...item, resource: resourceDetail };
        }
        return item;
      }));
    } catch (err) {
      console.error('获取资源详情失败:', err);
    }
  };

  // 添加状态变量用于控制删除资源关联的确认对话框
  const [removeResourceDialogOpen, setRemoveResourceDialogOpen] = useState(false);
  const [removeAllResourcesDialogOpen, setRemoveAllResourcesDialogOpen] = useState(false);
  const [resourceToRemove, setResourceToRemove] = useState<string>('');

  if (loading && page === 1) {
    return (
      <Box display="flex" justifyContent="center" p={3}>
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return <Alert severity="error">{error}</Alert>;
  }

  return (
    <Box sx={{ p: 3 }}>
      
      {/* 搜索和添加按钮 */}
      <Box sx={{ display: 'flex', mb: 2, gap: 2 }}>
        <TextField
          label="搜索促销活动"
          variant="outlined"
          size="small"
          value={searchQuery}
          onChange={handleSearchChange}
          sx={{ flexGrow: 1 }}
        />
        <FormControl variant="outlined" size="small" sx={{ minWidth: 120 }}>
          <InputLabel id="search-type-label">搜索类型</InputLabel>
          <Select
            labelId="search-type-label"
            value={searchType}
            onChange={handleSearchTypeChange}
            label="搜索类型"
          >
            <MenuItem value="id">ID</MenuItem>
            <MenuItem value="title">标题</MenuItem>
          </Select>
        </FormControl>
        {/* 删除搜索按钮 */}
        <Button
          variant="contained"
          color="primary"
          onClick={handleAddClick}
          startIcon={<AddIcon />}
        >
          新增促销活动
        </Button>
      </Box>
      
      {/* 错误提示 */}
      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>{error}</Alert>
      )}
      
      {/* 促销活动列表 */}
      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>ID</TableCell>
              <TableCell>标题</TableCell>
              <TableCell>活动规则</TableCell>
              <TableCell>开始时间</TableCell>
              <TableCell>结束时间</TableCell>
              <TableCell>折扣</TableCell>
              <TableCell>激活</TableCell>
              <TableCell>状态</TableCell>
              <TableCell>操作</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {!promotions || promotions.length === 0 ? (
              <TableRow>
                <TableCell colSpan={9} align="center">暂无促销活动</TableCell>
              </TableRow>
            ) : (
              promotions.map((promotion, index) => {
                const now = new Date();
                const startTime = new Date(promotion.startTime || '');
                const endTime = new Date(promotion.endTime || '');
                let status = '';
                
                // 计算活动状态
                if (now > endTime) {
                  status = '已结束';
                } else if (now >= startTime && now <= endTime) {
                  status = '进行中';
                  // 如果后端没有提供 inProgress 字段，我们在前端计算
                  if (promotion.inProgress === undefined) {
                    promotion.inProgress = true;
                  }
                } else {
                  status = '未开始';
                  // 如果后端没有提供 inProgress 字段，我们在前端计算
                  if (promotion.inProgress === undefined) {
                    promotion.inProgress = false;
                  }
                }
                
                return (
                  <TableRow key={promotion.id || promotion.promotionId || 'row-' + index}>
                    <TableCell>
                      {promotion.id ? String(promotion.id).substring(0, 8) + '...' : 
                       promotion.promotionId ? String(promotion.promotionId).substring(0, 8) + '...' : 'N/A'}
                    </TableCell>
                    <TableCell>{promotion.promotionTitle || 'N/A'}</TableCell>
                    <TableCell>{promotion.promotionRule || 'N/A'}</TableCell>
                    <TableCell>{promotion.startTime ? new Date(promotion.startTime).toLocaleString('zh-CN') : 'N/A'}</TableCell>
                    <TableCell>{promotion.endTime ? new Date(promotion.endTime).toLocaleString('zh-CN') : 'N/A'}</TableCell>
                    <TableCell>{promotion.discount !== undefined ? promotion.discount : 'N/A'}</TableCell>
                    <TableCell>
                      <Chip 
                        label={promotion.inProgress ? '是' : '否'} 
                        color={promotion.inProgress ? 'success' : 'default'} 
                        size="small" 
                        variant="outlined" 
                      />
                    </TableCell>
                    <TableCell>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <Chip 
                          label={status} 
                          color={status === '进行中' ? 'success' : status === '已结束' ? 'error' : 'warning'} 
                          size="small" 
                          variant="outlined" 
                        />
                      </Box>
                    </TableCell>
                    <TableCell>
                      <IconButton 
                        size="small" 
                        color="primary" 
                        onClick={() => handleEditClick(promotion)}
                        title="编辑"
                      >
                        <EditIcon fontSize="small" />
                      </IconButton>
                      <IconButton 
                        size="small" 
                        color="primary" 
                        onClick={() => handleLinkResourcesClick(promotion)}
                        title="关联资源"
                      >
                        <LinkIcon fontSize="small" />
                      </IconButton>
                      <IconButton 
                        size="small" 
                        color="error" 
                        onClick={() => handleDeleteClick(promotion)}
                        title="删除"
                      >
                        <DeleteIcon fontSize="small" />
                      </IconButton>
                    </TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </TableContainer>

      <Box sx={{ display: 'flex', justifyContent: 'center', mt: 2 }}>
        <Pagination 
          count={totalPages} 
          page={page} 
          onChange={handlePageChange} 
          color="primary" 
        />
      </Box>

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
      >
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <DialogContentText>
            确定要删除促销活动 "{selectedPromotion?.promotionTitle}" 吗？此操作将同时删除该活动的所有关联资源，且不可撤销。
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>取消</Button>
          <Button onClick={handleDeleteConfirm} color="error" autoFocus>
            删除
          </Button>
        </DialogActions>
      </Dialog>

      {/* 表单对话框 */}
      <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={zhCN}>
        <Dialog
          open={formDialogOpen}
          onClose={() => setFormDialogOpen(false)}
          maxWidth="md"
          fullWidth
        >
          <DialogTitle>{isEditMode ? '编辑促销活动' : '新建促销活动'}</DialogTitle>
          <DialogContent>
            <Grid container spacing={2} sx={{ mt: 1 }}>
              <Grid item xs={12}>
                <TextField
                  label="标题"
                  fullWidth
                  value={formData.title}
                  onChange={(e) => handleFormChange('title', e.target.value)}
                  error={!!formErrors.title}
                  helperText={formErrors.title}
                />
              </Grid>
              <Grid item xs={12}>
                <TextField
                  label="活动规则"
                  fullWidth
                  multiline
                  rows={3}
                  value={formData.promotionRule}
                  onChange={(e) => handleFormChange('promotionRule', e.target.value)}
                  error={!!formErrors.promotionRule}
                  helperText={formErrors.promotionRule}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <DateTimePicker
                  label="开始时间"
                  value={formData.startTime}
                  onChange={(newValue) => handleFormChange('startTime', newValue)}
                  slotProps={{
                    textField: {
                      fullWidth: true,
                      error: !!formErrors.startTime,
                      helperText: formErrors.startTime
                    },
                    // 确保日期选择器弹出层完全可见，并向上展示
                    popper: {
                      sx: { zIndex: 1500 }, // 提高z-index确保不被其他元素遮挡
                      placement: 'top-start' // 设置弹出方向为向上
                    },
                    // 确保移动端也能完全显示
                    mobilePaper: {
                      sx: { 
                        maxHeight: '80vh',
                        overflowY: 'auto'
                      }
                    }
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <DateTimePicker
                  label="结束时间"
                  value={formData.endTime}
                  onChange={(newValue) => handleFormChange('endTime', newValue)}
                  slotProps={{
                    textField: {
                      fullWidth: true,
                      error: !!formErrors.endTime,
                      helperText: formErrors.endTime
                    },
                    // 确保日期选择器弹出层完全可见，并向上展示
                    popper: {
                      sx: { zIndex: 1500 }, // 提高z-index确保不被其他元素遮挡
                      placement: 'top-start' // 设置弹出方向为向上
                    },
                    // 确保移动端也能完全显示
                    mobilePaper: {
                      sx: { 
                        maxHeight: '80vh',
                        overflowY: 'auto'
                      }
                    }
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  label="折扣"
                  type="number"
                  fullWidth
                  value={formData.discount}
                  onChange={(e) => handleFormChange('discount', parseFloat(e.target.value))}
                  error={!!formErrors.discount}
                  helperText={formErrors.discount}
                  InputProps={{ inputProps: { min: 0, step: 0.01 } }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormControlLabel
                  control={
                    <Switch
                      checked={formData.isActive}
                      onChange={(e) => handleFormChange('isActive', e.target.checked)}
                    />
                  }
                  label="活动状态"
                />
                <Typography variant="caption" color="text.secondary" display="block">
                  {formData.isActive ? '活动已激活' : '活动已停用'}
                </Typography>
              </Grid>
            </Grid>
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setFormDialogOpen(false)}>取消</Button>
            <Button onClick={handleFormSubmit} color="primary" variant="contained">
              保存
            </Button>
          </DialogActions>
        </Dialog>
      </LocalizationProvider>

      {/* 关联资源对话框 */}
      <Dialog
        open={linkResourceDialogOpen}
        onClose={() => setLinkResourceDialogOpen(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>关联资源到 "{selectedPromotion?.promotionTitle}"</DialogTitle>
        <DialogContent>
          <Box sx={{ mt: 2, mb: 3 }}>
            <Autocomplete
              multiple
              options={resources}
              getOptionLabel={(option) => `${option.title} (ID: ${option.id})`}
              value={selectedResources}
              onChange={(event, newValue) => setSelectedResources(newValue)}
              renderInput={(params) => (
                <TextField
                  {...params}
                  label="选择资源"
                  placeholder="搜索资源..."
                  helperText="可以选择多个资源关联到此促销活动"
                />
              )}
              renderOption={(props, option) => (
                <li {...props} key={option.id}>
                  {option.title} (ID: {option.id})
                </li>
              )}
            />
          </Box>
          
          {/* 已关联资源列表 */}
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mt: 3, mb: 1 }}>
            <Typography variant="h6">已关联资源列表</Typography>
            {linkedResources.length > 0 && (
              <Button 
                variant="outlined" 
                color="error" 
                size="small" 
                startIcon={<DeleteIcon />}
                onClick={handleRemoveAllResourcesClick}
              >
                删除所有关联
              </Button>
            )}
          </Box>
          {linkedResources.length === 0 ? (
            <Typography color="text.secondary">暂无关联资源</Typography>
          ) : (
            <TableContainer component={Paper} sx={{ mt: 1 }}>
              <Table size="small">
                <TableHead>
                  <TableRow>
                    <TableCell>ID</TableCell>
                    <TableCell>标题</TableCell>
                    <TableCell>描述</TableCell>
                    <TableCell>操作</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {linkedResources.map((item, index) => {
                    // 从API返回的数据结构中提取资源信息
                    const resource = item.resource || {
                      id: item.resourceId,
                      title: `资源 ${item.resourceId}`,
                      description: ''
                    };
                    
                    // 如果没有资源详情，则获取资源详情
                    if (!item.resource && item.resourceId) {
                      fetchResourceDetail(item.resourceId);
                    }
                    
                    return (
                      <TableRow key={item.relationId || `resource-${index}`}>
                        <TableCell>{resource.id || item.resourceId}</TableCell>
                        <TableCell>{resource.title}</TableCell>
                        <TableCell>{resource.description?.substring(0, 50)}{resource.description?.length > 50 ? '...' : ''}</TableCell>
                        <TableCell>
                          <IconButton 
                            size="small" 
                            color="error" 
                            onClick={() => handleRemoveResourceClick(item.relationId)}
                            title="解除关联"
                          >
                            <DeleteIcon fontSize="small" />
                          </IconButton>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </TableContainer>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setLinkResourceDialogOpen(false)}>取消</Button>
          <Button 
            onClick={handleLinkResourcesSubmit} 
            color="primary" 
            variant="contained"
            disabled={selectedResources.length === 0}
          >
            关联
          </Button>
        </DialogActions>
      </Dialog>

      {/* 提示消息 */}
      <Snackbar 
        open={snackbar.open} 
        autoHideDuration={6000} 
        onClose={handleSnackbarClose}
      >
        <Alert 
          onClose={handleSnackbarClose} 
          severity={snackbar.severity} 
          sx={{ width: '100%' }}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>

      {/* 删除单个资源关联确认对话框 */}
      <Dialog
        open={removeResourceDialogOpen}
        onClose={() => setRemoveResourceDialogOpen(false)}
      >
        <DialogTitle>确认解除关联</DialogTitle>
        <DialogContent>
          <DialogContentText>
            确定要解除此资源的关联吗？此操作不可撤销。
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setRemoveResourceDialogOpen(false)}>取消</Button>
          <Button onClick={handleRemoveResource} color="error" autoFocus>
            解除关联
          </Button>
        </DialogActions>
      </Dialog>

      {/* 删除所有资源关联确认对话框 */}
      <Dialog
        open={removeAllResourcesDialogOpen}
        onClose={() => setRemoveAllResourcesDialogOpen(false)}
      >
        <DialogTitle>确认删除所有关联</DialogTitle>
        <DialogContent>
          <DialogContentText>
            确定要删除此促销活动的所有资源关联吗？此操作不可撤销。
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setRemoveAllResourcesDialogOpen(false)}>取消</Button>
          <Button onClick={handleRemoveAllResources} color="error" autoFocus>
            删除所有关联
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default PromotionManagement;